package pro.common.config;

import pro.common.constant.DbType;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

public class ConnConfig {

    public static final ConnConfig inStance;

    static{
        try {
            inStance = new ConnConfig();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error to create instance");
        }
    }
    private ConnConfig() throws IOException {
        String configFile = "/config.properties";
        DbType dbtype = getDbType();

        if (dbtype == DbType.MYSQL){
            configFile = "mysqlConfig.properties";
        }
        InputStream stream = ConnConfig.class.getResourceAsStream(configFile);

        Properties p = new Properties();
        p.load(stream);

        if (dbtype == DbType.MYSQL){
            setDriver(p.getProperty("driver_mysql"));
        }

        setUrl(p.getProperty("url"));
        setPassword(p.getProperty("password"));
        setUserName(p.getProperty("username"));

        setBasePath(p.getProperty("base_path"));

    }
    private static final DbType dbType = DbType.ORACLE;
    private String driver = "";
    private String url = null;
    private String userName = null;
    private String password = null;

    private  String basePath = "";

    public static DbType getDbType() {
        return dbType;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public Connection getConn(){
        try {
            Driver myDriver =  (Driver) Class.forName(this.driver).newInstance();

            Properties p = new Properties();
            p.put("user", this.getUserName());
            p.put("password", this.getPassword());

            return myDriver.connect(this.url, p);

        } catch (Exception e) {
            throw new IllegalArgumentException("Get Connection Error.");
        }

    }

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }
}
